$(function() {
    $("#deadline").datetimepicker({dateFormat: 'yy-mm-dd'});
});

$(document).ready(function(){

    $("#add_question").click( function(){
        var question_id = $("#question_count").val();
        question_id++;
        $("#question_count").val(question_id); //set the new count value
        $("#new_question_tmpl").tmpl({"question_id":question_id}).appendTo("#form_questions");
    });

    //$(".add_option").click( function(){
    $(".add_option").live('click', function() {
//        console.log("inside add option");
        var qIdStr = $(this).attr('id');
        var qId = parseInt(qIdStr.substr(12,2)); //varla með fleiri en 99 spurningar
  //      console.log("Question id: " + qId);
        var cssOptionCountId = "#question_" + qId + "_option_count";
        var cssAddToId = "#options_q" + qId;
        var option_id = parseInt($(cssOptionCountId).val());
        option_id++;
        $(cssOptionCountId).val(option_id); //set the new option count value
        $("#new_option_tmpl").tmpl({"question_id":qId,"option_id":option_id}).appendTo(cssAddToId);
    //    console.log("done...");
    });

    //tooltip
    $('.link_take_exams').qtip(
        {
            content: 'Click here to take an exam!' // Give it some content, in this case a simple string
        });
    //tooltip
    $('.link_stats_exams').qtip(
        {
            content: 'View this exam statistics!' // Give it some content, in this case a simple string
        });

    $('input:radio').qtip(
        {
            content: 'Click here to set this answer as correct!' // Give it some content, in this case a simple string
    });

    $('input:checkbox').qtip(
        {
            content: 'Not not used in this version :( \n The value is hard coded to enabled=true'
    });

});

function saveExamFormWS()
{
    var postData = getJsonExamObject();
    if (!validateForm(postData))
        return false; //if form is not valid stop and return

    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "/exam/create/",
        data: JSON.stringify(postData),
        dataType: "json",
        crossDomain: true,
        success: function (data) {
            $("#page-wrap").html('');
            $("#create_result_tmpl").tmpl(data).appendTo("#content");
        },
        error: function (xhr, err) {
            setMsgAndReturn("Error saving:" + err);
        }
    });
    return null;
}

function getJsonExamObject(){
    var examJsonObj;
    var numQuestions = $("#question_count").val(); //number of questions
    // get exam form values
    var title = $("#title").val();
    var descr = $("#description").val();
    $('#deadline').removeAttr('readonly');
    var deadl = $("#deadline").val();
    $('#deadline').attr('readonly', true);
  //  var enabl = $("#enabled").val();
    var enabl = 1; //

    //array for questions objects
    var questionArr = new Array();

    // iterate through all questions
    for (var i = 1; i <= numQuestions; i++ ){
        var optionArr = new Array(); //a new option array for each question
        var cssQuestionStr = "#question_" + i; //question_1
        var fieldQuestion = $(cssQuestionStr).val(); //get value of question nr. i
        var cssCountOptionsStr = cssQuestionStr + "_option_count"; //question1_option_count
        var numOptions = $(cssCountOptionsStr).val(); // number of options per question

        var cssRadioStr = "input:radio[name=q"+ i +"]:checked";
        var correct =  $(cssRadioStr).val(); //get which correct answer
        //console.log("Correct value= " + correct);

        //iterate through all options per questions
        //console.log("number of options:" + numOptions);
        for (var j=1; j<= numOptions; j++)
        {
            //q1_o1
            var cssOptionStr = "#q"+ i +"_o" + j;
          //  console.log(cssOptionStr);
            var fieldOption = $(cssOptionStr).val(); //get value of each option per question
            var isCorrect = 0;
            if (j === Number(correct))
                isCorrect = 1;
            console.log("correct value option is:" + correct + " | j:"+j + " isCorrect:" + isCorrect);
            optionArr.push( { "option":fieldOption, "correct": isCorrect } ) ; //store json object for each option in optionArr
        } //loop for options per question ends

        /* add new question object to question array */
        questionObj = {"question" : fieldQuestion,"options": optionArr };
        questionArr.push( questionObj );
    } //loop for questions ends

    //finally create the complete Exam json object
    examJsonObj = {"title" : title, "description" : descr, "deadline" : deadl, "enabled" : parseInt(enabl), "questions" : questionArr };
    return examJsonObj;
}

function setMsgAndReturn(msg){
    $("#message").text(msg);
    return false;
}

function validateForm(frmData){
    if (frmData.title.length < 1)
       return setMsgAndReturn("Exam title should be at least 1 character!");

    if (frmData.deadline.length < 1)
        return setMsgAndReturn("You forgot to set the deadline!");

    var qArr = frmData["questions"];

    for (var q in qArr){
        if (qArr[q].question.length < 1)
            return setMsgAndReturn("Question field is not filled out!");
        var oArr = qArr[Number(q)].options
        for (var o in oArr){
            if (oArr[o].option.length < 1)
                return setMsgAndReturn("Answer field is not filled out!")

        }
    }
    return true; //form is valid
}

function getJsonStudentExamObject(){
// iterate through all questions
    var answerArr = new Array();
    var exId = $("#eid").val();

    //loop through all questions
    $('.question').each(function(index) {
        var qid = $(this).val(); // get question id
        var cssRadioStr= "input:radio[name=q"+ qid + "]:checked"; //get user answer
        console.log("qid:" + qid);
        var correct =  $(cssRadioStr).val(); //get which correct answer
        if (correct === undefined)
            correct = -1;
        console.log("question id:" + qid + " answered id:" + correct);

        answerArr.push({"question_id": Number(qid), "answered_option":Number(correct)});
    });

    return {"eid": Number(exId), "answers":answerArr};
}


// Function that saves from by AJAX
function saveStudentExamFormWS(){
    var postData = getJsonStudentExamObject();
    var exId = $("#eid").val();
    console.log(postData);
    console.log(JSON.stringify(postData));
    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "/exam/take/" + exId + "/",
        data: JSON.stringify(postData),
        dataType: "json",
        crossDomain: true,
        success: function (data) {

            if (Boolean(data['success']) === 1)
            {
                $("#page-wrap").html('');
                $("#create_result_tmpl").tmpl(data).appendTo("#content");
            }
            else
                setMsgAndReturn("You cannot take an exam more than once!");

        },
        error: function (xhr, err) {
            setMsgAndReturn("Error saving:" + err);
        }
    });
    return null;
}



